<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @add="add"></TodoHeader>
    <!-- 主体部分 -->
    <TodoMain :list="siftInProgress" @delList="delList" @change="change"></TodoMain>
    <!-- 底部部分 -->
    <TodoFooter
      :list="list"
      :call="call"
      @purge="purge"
      @handoff="handoff"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      call: 'all',
      list: JSON.parse(localStorage.getItem('toDoList'))|| [
        { id: 1, name: '吃饭', isDone: true },
        { id: 2, name: '睡觉', isDone: false },
        { id: 3, name: '打豆豆', isDone: true },
      ],
    }
  },
  methods: {
    delList(id) {
      this.list = this.list.filter((item) => {
        return item.id !== id
      })
    },
    change(id) {
      const res = this.list.find((item) => item.id === id)
      res.isDone = !res.isDone
    },
    add(value) {
      const obj = { id: +new Date(), name: value, isDone: false }
      this.list = [obj, ...this.list]
    },
    purge() {
      this.list = this.list.filter((item) => !item.isDone)
    },
    handoff(value) {
      this.call = value
    },
  },
  computed: {
    siftInProgress() {
      switch (this.call) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item)=>item.isDone===false)
        case 'completed':
          return this.list.filter((item)=>item.isDone===true)
        default:
          return this.list
      }
    },
  },
  watch:{
    list:{
      deep:true,
      handler(newValue){
        localStorage.setItem('toDoList',JSON.stringify(newValue))
      }
    }
  }
}
</script>

<style></style>
